package com.stone.mpandroidchartdemo;

import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;
import java.util.List;

public class BarChartActivity extends AppCompatActivity implements OnChartValueSelectedListener {

    private BarChart mBarChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bar_chart);

        // 初始化view
        initView();

        // 初始化BarChart
        initBarChart();

        // 给BarChart设置数据
        setData(12, 50);
    }

    /**
     * 初始化view
     */
    private void initView() {
        mBarChart = findViewById(R.id.bar_chart);
    }

    /**
     *  初始化BarChart
     */
    private void initBarChart() {

        // 设置数值选择监听，点击后回到数据
        mBarChart.setOnChartValueSelectedListener(this);

        // 设置柱状阴影（true：有阴影
        mBarChart.setDrawBarShadow(false);

        // 设置数值显示位置（true:柱状上方
        mBarChart.setDrawValueAboveBar(true);

        // 设置图标描述文字是否展示（true：展示
        mBarChart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mBarChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        mBarChart.setPinchZoom(false);

        mBarChart.setDrawGridBackground(false);
        // mChart.setDrawYLabels(false);

        String[] month = getResources().getStringArray(R.array.month);

        IAxisValueFormatter xAxisFormatter = new MonthAxisValueFormatter(month);

        //region X轴的设置
        XAxis xAxis = mBarChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置字体。
        // xAxis.setTypeface(mTfLight);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day

        xAxis.setLabelCount(7);
        xAxis.setValueFormatter(xAxisFormatter);

        //endregion Y轴的设置，分为左侧Y和右侧Y
        IAxisValueFormatter custom = new StoneYAxisValueFormatter();

        // 获取左侧Y的实例
        YAxis leftAxis = mBarChart.getAxisLeft();
        //leftAxis.setTypeface(mTfLight);
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);

        // y轴最上端，的距离，根据最大值决定高度
        leftAxis.setSpaceTop(15f);
        // 设置x轴最低的距离，设置为0，表示和x轴重合
        //leftAxis.setSpaceBottom(0);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        // 获取右侧Y
        YAxis rightAxis = mBarChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        //rightAxis.setTypeface(mTfLight);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        //leftAxis.setSpaceBottom(0);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        // region 图例设置
        Legend l = mBarChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);
        // endregion


    }

    /**
     * 给BarChart设置数据
     * @param count
     * @param range
     */
    private void setData(int count, float range) {


        List<BarEntry> list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            // 产生一个随机数
            float val = (float) (Math.random() * range);
            list.add(new BarEntry(i + 1, val));
        }

        BarDataSet set1;

        if (mBarChart.getData() != null &&
                mBarChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mBarChart.getData().getDataSetByIndex(0);
            set1.setValues(list);
            mBarChart.getData().notifyDataChanged();
            mBarChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(list, "The year 2018");

            set1.setDrawIcons(false);

            // 设置颜色，最好和数据的size一样，如果不等，那就是循环取色
            set1.setColors(ColorTemplate.MATERIAL_COLORS);

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            //data.setValueTypeface(mTfLight);
            // 设置柱状图的宽度
            data.setBarWidth(0.8f);

            mBarChart.setData(data);

        }

    }

    //region 点击效果处理
    @Override
    public void onValueSelected (Entry e, Highlight h){

        //只做了获取值的处理
        BarEntry barEntry = (BarEntry) e;
        System.out.println("点击后获取的值：" + barEntry.getY());
    }

    @Override
    public void onNothingSelected () {

    }

    //endregion
}
